<template>
	<mu-container>
		<mu-form ref="form" class="mu-demo-form" :model="validateForm" :label-position="labelPosition" label-width="100">
			<mu-form-item prop="money" label="金额" :rules="moneyRules">
				<mu-text-field v-model="validateForm.money"></mu-text-field>
			</mu-form-item>
			<mu-form-item prop="remarks" label="备注" :rules="remarksRules">
				<mu-text-field multi-line :rows="3" :rows-max="6" v-model="validateForm.remarks"></mu-text-field>
			</mu-form-item>
			<mu-form-item>
				<mu-button color="primary" @click="submit">提交</mu-button>
				<mu-button @click="clear">重置</mu-button>
			</mu-form-item>
		</mu-form>
	</mu-container>

</template>

<script>
	export default {
		name: 'Bookkeeping',
		data() {
			return {
				moneyRules: [{
						validate: (val) => !!val,
						message: '必须填写金额'
					},
					{
						validate: (val) => {
							var reg = /^[0-9,.]*$/ //^[-\+]?\d+(\.\d+)?$/;
							return reg.test(val);
						},
						message: '金额必须为数字'
					}
				],
				remarksRules: [{
					validate: (val) => !!val,
					message: '必须填写备注'
				}],
				labelPosition: 'left',
				validateForm: {
					money: '',
					remarks: ''
				}


			}
		},
		methods: {
			submit() {
				this.$refs.form.validate().then((result) => {
					if (result) {
						this.addBill();
					}
					console.log('form valid: ', result)
				});
			},
			addBill(){
				//获取值
				let self = this;
				var money = this.validateForm.money;
				var remarks = this.validateForm.remarks;
				
				var querystring = require("querystring");
				var params = querystring.stringify({
					money: money,
					remarks: remarks
				});
				self.$ajax({
						method: "post",
						url: "/bill/addBill",
						data: params
					})
					.then(function (res) {
						if (res.data.code == 200) {
							self.clear();
							// var name = self.$route.query.redirect || 'homePage';
							self.$toast.success('记账成功');
							//获取登录成功后要跳转的路由。
							self.$router.push({
								name: 'Bookkeeping'
							});
						} else {
							self.clear();
							self.$toast.error(res.data.content);
							
						}
					})
					.catch(function (err) {
						console.log(err);
						self.clear();
						
					});
			},
			
			clear() {
				this.$refs.form.clear();
				this.validateForm = {
					money: '',
					remarks: ''
				};
			}
		}
	}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
	.mu-demo-form {
		width: 100%;
		max-width: 460px;
	}
</style>
